import "babel-polyfill";
import Vue from 'vue';
import VueResource from 'vue-resource'
import iView from 'iview';
import {router} from './router/index';
import addApi from '@/common/router/addApi';
import {routers, otherRouter, appRouter} from './router/router';
import store from './store';
import App from './app.vue';
import 'iview/dist/styles/iview.css';
import Util from '@/common/libs/util';
import Cookies from 'js-cookie';
import iviewArea from 'iview-area';

Vue.use(iviewArea);

Vue.use(iView);
Vue.use(VueResource);
Vue.http.options.emulateJSON = true;

var temp = {}
// 添加路由前后事件
router.beforeEach((to, from, next) => {
    iView.LoadingBar.start();
    Util.title(to.meta.title);
    if (Cookies.get('access') != "member" && to.name !== 'login') { // 判断是否未登录且前往的页面不是登录页
        next({
            name: 'login'
        });
    } else if(Cookies.get('access') != "member" && to.name == 'login') {
        window.location.href = Util.getRuntimeUrl("index", "index/login");
    } else if (Cookies.get('access') == "member" && to.name === 'login') { // 判断是否已经登录且前往的是登录页
        Util.title();
        next({
            name: 'home_index'
        });
    } else {
        const curRouterObj = Util.getRouterObjByName([otherRouter, ...appRouter], to.name);
        if (curRouterObj && curRouterObj.permission !== undefined) { // 需要判断权限的路由
            if (Cookies.get('access') == "member" && Util.showThisRoute(curRouterObj.permission, temp.vm.$store.state.user.info.permission)) {
                Util.toDefaultPage([otherRouter, ...appRouter], to.name, router, next); // 如果在地址栏输入的是一级菜单则默认打开其第一个二级菜单的页面
            } else {
                next({
                    replace: true,
                    name: 'error-403'
                });
            }
        } else { // 没有配置权限的路由, 直接通过
            Util.toDefaultPage([...routers], to.name, router, next);
        }
    }
  });
  
  router.afterEach((to) => {
    iView.LoadingBar.finish();
    window.scrollTo(0, 0);
  });

temp.vm = new Vue({
    el: '#app',
    router: router,
    store: store,
    render: h => h(App),
    mounted () {
    },
    created() {
        // 添加自定义接口函数
        addApi(this);
    }
});

